package com.example.springsecurity.controller;

import com.example.springsecurity.entity.UserInfo;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: LoginController
 * Author:   WGG
 * Date:    2022-12-2022/12/19-14:41
 * Version: 1.0
 * Description:
 */
@RestController
public class LoginController {

    @RequestMapping("/test")
    public String login(){
        return "登录成功";
    }

    @GetMapping("/indexout")
    public String logout(){
        return "难道是没登录";
    }


    @GetMapping("/index")
    public String index(){
        return "hello";
    }

    @GetMapping("/test/index")
    public String testindex(){
        return "success";
    }

    @PostMapping("/user/login")
    public String log(){
        return "login success";
    }

    @GetMapping("/hellose")
    @Secured({"ROLE_管理员","ROLE_admin"})//给当前的方法授权
    public String testSecurity(){
        return "hello,springSecurity";
    }
     @GetMapping("/hellepro")
    @PreAuthorize("hasAuthority('ROLE_普通用户')")//表示在方法执行之前进行权限的校验
    public String testHello(){
        return "hello,管理员";
    }

    @RequestMapping("/getAll")
    @PreAuthorize("hasRole('ROLE_管理员')")
    @PostFilter("filterObject.username == 'admin1'") //过滤方法返回值中的数据 filterObject表示过滤的对象
    public List<UserInfo> getAllUser(){
        ArrayList<UserInfo> list = new ArrayList<UserInfo>();
        list.add(new UserInfo(1,"admin1","123456"));
        list.add(new UserInfo(1,"admin2","123456"));
        return list;
    }

    @RequestMapping("/getTestPreFilter")
    @PreAuthorize("hasRole('ROLE_管理员')")
    @PreFilter(value = "filterObject.id%2==0")//表示过滤传入参数
    public List<UserInfo> getTestPreFilter(@RequestBody List<UserInfo> list){
        list.forEach(t->{
            System.out.println(t.getId()+"\t"+t.getUsername());
        });
        return list;
    }
}
